package org.srilankaliving.analytics;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;


import java.io.File;
import java.io.IOException;

public class FinalQoLAnalyser extends Configured implements Tool {

    public static class FinalQoLMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String splitarray[] = line.split("\t");
            if (splitarray.length == 2) {
                String ethinicity = splitarray[0].trim();
                String qolType = splitarray[1].trim();
                System.out.println("========== MAP =======: " + qolType + " : " + ethinicity);
                context.write(new Text(qolType), new Text(ethinicity));
            }
        }
    }

    public static class FinalQoLReducer extends Reducer<Text, Text, Text, IntWritable> {

        private MultipleOutputs multipleOutputs;

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String workingDir = System.getProperty("user.dir");
            if (key.toString().equals(QOLUtils.TYPE_A)) {
                for (Text value : values) {
                    multipleOutputs.write(key, value, (workingDir + "/src/main/resources/final_qol/A/"));
                }
                context.progress();
            } else if (key.toString().equals(QOLUtils.TYPE_B)) {
                for (Text value : values) {
                    multipleOutputs.write(key, value, (workingDir + "/src/main/resources/final_qol/B/"));
                }
                context.progress();
            } else if (key.toString().equals(QOLUtils.TYPE_C)) {
                for (Text value : values) {
                    multipleOutputs.write(key, value, (workingDir + "/src/main/resources/final_qol/C/"));
                }
                context.progress();
            } else if (key.toString().equals(QOLUtils.TYPE_D)) {
                for (Text value : values) {
                    multipleOutputs.write(key, value, (workingDir + "/src/main/resources/final_qol/D/"));
                }
                context.progress();
            } else if (key.toString().equals(QOLUtils.TYPE_E)) {
                for (Text value : values) {
                    multipleOutputs.write(key, value, (workingDir + "/src/main/resources/final_qol/E/"));
                }
                context.progress();
            }
        }

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            multipleOutputs.close();
        }

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            multipleOutputs = new MultipleOutputs(context);
        }
    }


    /*Count QOL Type */
    public static class QOLTypeMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String splitarray[] = line.split("\t");
            if (splitarray.length == 2) {
                String qolType = splitarray[0].trim();
                String ethinicity = splitarray[1].trim();
                System.out.println("========== MAP =======: " + qolType + " : " + ethinicity);
                context.write(new Text(ethinicity), new IntWritable(1));
            }
        }
    }

    public static class QOLTypeReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable cnt : values) {
                System.out.println("KEY : " + key);
                System.out.println("VAL : " + cnt);
                sum += 1;
            }
            context.write(new Text(key), new IntWritable(sum));
        }
    }


    public static void main(String[] args) throws IOException, Exception {
        int res = ToolRunner.run(new Configuration(), new FinalQoLAnalyser(), args);
        System.exit(res);
    }


    public int run(String[] args) throws Exception {
        /*Copy Required files from previous MPRed jobs*/
        QOLUtils.copyFile(QOLUtils.COORELATION_OUT_PATH + File.separator + "part-00000",
                QOLUtils.QOL_FINAL_DATA_IN_PATH + File.separator + "part-00000");

        Configuration conf = new Configuration();

        Job job = new Job(conf, "FinalQoLAnalyser");


        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setMapperClass(FinalQoLMapper.class);
        job.setReducerClass(FinalQoLReducer.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(QOLUtils.QOL_FINAL_DATA_IN_PATH));
        FileOutputFormat.setOutputPath(job, new Path(QOLUtils.QOL_FINAL_DATA_OUT_PATH));

        /*MultipleOutputs.addNamedOutput(job, "A", TextOutputFormat.class, IntWritable.class, Text.class);
        MultipleOutputs.addNamedOutput(job, "B", TextOutputFormat.class, IntWritable.class, Text.class);
        MultipleOutputs.addNamedOutput(job, "C", TextOutputFormat.class, IntWritable.class, Text.class);
        MultipleOutputs.addNamedOutput(job, "D", TextOutputFormat.class, IntWritable.class, Text.class);
        MultipleOutputs.addNamedOutput(job, "E", TextOutputFormat.class, IntWritable.class, Text.class);*/

        job.submit();
        job.waitForCompletion(true);

        createJobForQOLType("A");
        createJobForQOLType("B");
        createJobForQOLType("C");
        createJobForQOLType("D");
        createJobForQOLType("E");

        return 0;
    }


    private static void createJobForQOLType(String qolType) throws IOException, ClassNotFoundException, InterruptedException {
        Job cnterJob = new Job(new Configuration(), "QOLCounter" + qolType);
        cnterJob.setOutputKeyClass(Text.class);
        cnterJob.setOutputValueClass(Text.class);

        cnterJob.setMapperClass(QOLTypeMapper.class);
        cnterJob.setReducerClass(QOLTypeReducer.class);

        cnterJob.setOutputKeyClass(Text.class);
        cnterJob.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(cnterJob, new Path(QOLUtils.QOL_FINAL_DATA + File.separator + qolType));
        FileOutputFormat.setOutputPath(cnterJob, new Path(QOLUtils.QOL_FINAL_DATA + File.separator +
                qolType + "/output"));

        cnterJob.submit();
        cnterJob.waitForCompletion(true);

    }
}